package ilincar.systemcore.model;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;

/**
 * Created by ilincar on 2016/11/21.
 */

public enum  CllThread {

    INSTANCE;

    private static final String IO_THREAD = "I/O";

    private HandlerThread mIOThread;

    // 用于执行I/O 操作的handler
    private Handler mFileHandler;

    // 主线程Handler
    private volatile Handler mMainThreadHandler ;

    CllThread(){
        init();
    }

    private void init(){
        mIOThread = new HandlerThread(IO_THREAD);
        mIOThread.setPriority(Thread.NORM_PRIORITY);
        mIOThread.start();
        mFileHandler = new Handler(mIOThread.getLooper());
    }

    private void dispose(){
        mIOThread.getLooper().quit();
        mIOThread = null;
        mFileHandler = null;
    }

    private Handler getIOThreadHandler(){
        return mFileHandler;
    }

    public void runOnWorkerThread(final Runnable runnable){
        if(runnable != null){
            CllThread.INSTANCE.getIOThreadHandler().post(new Runnable() {
                @Override
                public void run() {
                    runnable.run();
                }
            });
        }
    }

    private Handler getMainThreadHandler(){
        if(mMainThreadHandler == null){
            synchronized (CllThread.class){
                mMainThreadHandler = new Handler(Looper.getMainLooper());
            }
        }
        return mMainThreadHandler;
    }
}
